package com.payment.notify.message;

import javax.jms.Queue;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.stereotype.Component;
import org.springside.modules.utils.mapper.JsonMapper;

import com.payment.common.exceptions.ServiceException;
import com.payment.notify.core.NotifyPersist;
import com.payment.notify.core.NotifyQueue;
import com.payment.notify.domain.TblTradeNotifyRecord;
import com.payment.notify.enums.NotifyStatusEnum;
import com.payment.notify.service.NotifySerivce;

/**
 * 类名：ConsumerMessageListener.java<br>
 * 描述：MQ 消费者 Listener<br>
 * 创建者：XINJF<br>
 * 创建日期：2018年4月24日下午1:57:56<br>
 * 版本：1.0<br>
 * 修改者：<br>
 * 修改日期：<br>
 */

@Component
public class ConsumerMessageListener {

	private static final Log log = LogFactory.getLog(ConsumerMessageListener.class);

	@Autowired
	private JmsMessagingTemplate jmsMessageTemplate; 
	@Autowired
	private Queue queue;

	@Autowired
	private NotifyQueue notifyQueue;
	@Autowired
	private NotifySerivce notifyService;
	@Autowired
	private NotifyPersist notifyPersist;

	@SuppressWarnings("static-access")
	@JmsListener(destination = "notify.queue")  
	public synchronized void receiveMessage(String message) {
		try {
			System.out.println("接收后的数据==" + message);
			final String ms = message;
			System.out.println("== receive message:" + ms);
			TblTradeNotifyRecord notifyRecord = JsonMapper.INSTANCE.fromJson(ms, TblTradeNotifyRecord.class);
			System.out.println("notifyRecord=="+notifyRecord);
			if (notifyRecord == null) {
				return;
			}
			notifyRecord.setStatus(NotifyStatusEnum.CREATED.getValue());
			if (notifyRecord.getId() == null) {// 判断数据库中是否已有通知记录
				while (notifyService == null) {
					Thread.currentThread().sleep(1000); // 主动休眠，防止类notifyService未加载完成，监听服务就开启监听出现空指针异常
				}

				try {
					// 将获取到的通知先保存到数据库中
					Long notifyId = notifyPersist.saveNotifyRecord(notifyRecord);
					notifyRecord.setId(notifyId);
					//TODO 需要重新查找下数据 不能直接获使用ID进行发送
					// 添加到通知队列
					notifyQueue.addElementToList(notifyRecord);
				} 
//				catch (RpcException e) {

//					sendMessage()

//					log.error("RpcException :", e);
//				} 
				catch (ServiceException e) {
					log.error("ServiceException :", e);
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			log.error(e);
		}
	}
	
	public void sendMessage(final String message){  
		jmsMessageTemplate.convertAndSend(this.queue, message);  
    }  
}
